<?php
/**
 * Author: yann
 * QQ: 9197313
 * Date: 2018/12/11 0011
 * Time: 下午 3:56
 */

namespace app\api\job;

use think\Controller;
use think\queue\Job;

class Message extends Controller
{
    private $appid = 'wx15ccaeb7366b1ebf';
    private $appsecret = 'e24d76280d2bc22b770194b1d015f17f';

    public function fire(Job $job, $data)
    {
        //....这里执行具体的任务
        $data = json_decode($data,true);
        $res = $this->createTpl($data['openid'], $data['title'], $data['lid'], $data['form_id']);

        if(isset($res['errcode']) && $res['errcode'] == 41001)
        {
            $job->delete();
            print("<info>Hello Job has been done and deleted"."</info>\n");
        }else{
            print("<info>Hello Job has been faild"."</info>\n");
            $job->release(3); //$delay为延迟时间
        }
        if ($job->attempts() > 3) {
            //通过这个方法可以检查这个任务已经重试了几次了
        }
        //如果任务执行成功后 记得删除任务，不然这个任务会重复执行，直到达到最大重试次数后失败后，执行failed方法
        // $job->delete();
        // 也可以重新发布这个任务
        // $job->release($delay); //$delay为延迟时间
    }
    public function failed($data)
    {
        // ...任务达到最大重试次数后，失败了
    }
    public function jobDone($data)
    {
        print("<info>Job is Done status!"."</info> \n");
    }

    private function createTpl($openid,$goods,$lid,$form_id,$remark="您参与的活动正在开奖,点击查看中奖名单"){

        $template = array(
            "touser" => $openid,
            "template_id" => 'N88WIcwaosHU22silFGLS3oLG_ht33N6WMp4YRaCpy8',
            "page"  =>'pages/info/main?id='.$lid,
            "form_id" => $form_id,
            "data"=> array(
                'keyword1'  => array('value'=>$goods,'color'=>'#000000'),
                'keyword2'  => array('value'=>$remark,'color'=>'#c2262a')
            ),
            'emphasis_keyword'=>''
        );
        return $this->sendTplMsg($template);
    }

    private function sendTplMsg($data){
        $data = urldecode(json_encode($data));
        $access_token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=".$access_token;
        $res = $this->httpGet($url,$data);
        return json_decode($res,true);
    }
    private function httpGet($url,$data) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    private function getAccessToken() {
        $data = cache('access_token_json_'.$this->appid);
        if ($data['expire_time'] < time()) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appid&secret=$this->appsecret";
            $res = json_decode($this->httpGet($url,null));
            $access_token = $res->access_token;

            if ($access_token) {
                $data['expire_time'] = time() + 7100;
                $data['access_token'] = $access_token;
                cache('access_token_json_'.$this->appid,$data);
            }
        } else {
            $access_token = $data['access_token'];
        }
        return $access_token;
    }
}
